<?php
namespace app\admin\controller;
use app\admin\model\Admin;
use think\Controller;
use think\Db;

class Index extends Common
{
   public $user_id;
    /**
     * 构造方法
     */
    public function _initialize(){
        //定义系统的编码
        header("Content-Type:text/html; charset=utf-8");
        header('Content-Type:app/json; charset=utf-8');
        //登录ID
        $uid = session('uid');
    }
    //首页方法
    public function index()
    {
        $user_id = session('admin.id');
        $userinfo = DB::name('admin')->where(array('id'=>$user_id))->find();
        $this->assign('admin_name',$userinfo['username']);

        //验证是否已登录
        if(!$user_id){
            $this->redirect('Index/login');
        }

        return $this->fetch();
    }

    /**
     * 用户信息
     */
    public function user_show()
    {
        $user_id = session('admin.id');
        $user_info = DB::name('admin')->where(array('id'=>$user_id))->find();
        $this->assign('userinfo',$user_info);
        //halt($user_info);exit;

        return $this->fetch();
    }

    /**
     * 登录验证
     */
    public function login(){
        //表单提交
        if(request()->isPost()){
            //接收表单数据并传入模型
            $data = input();
            $res = (new Admin())->pass($data);
            if($res['valid']){
                //登录成功
                $this->success($res['msg'],'Index/index');
            }else{
                //登录失败
                $this->error($res['msg'],'Index/login');
            }

        }else{

            return $this->fetch();
        }


    }

    //退出登录
    public function log_out(){

        //清空session的用户信息
        session('admin','');
        //halt(session('admin'));exit;
        $this->redirect('Index/login');
    }

    //切换账号
    public function switch_account(){

        //退回登录界面
        $this->redirect('Index/login');
    }


    public function welcome(){


        return $this->fetch();
    }


}
